<?php

namespace Cktadmin\Controller;

use Common\Controller\BasicAdmin;
use Common\Service\DataService;

class ChangeController extends BasicAdmin {

    public $table = 'transaction';

    public function index() {
        $this->title = '充值记录';
        $where = array('type' => 1);
        $get = I('get.');
        (isset($get['key']) && $get['key'] !== '') && $where['user_name|order_no|alipay_account'] = array('like', "%{$get['key']}%");
        $count = M($this->table)->where($where)->count();
        $db = M($this->table)->where($where)->order('add_time desc');
        return parent::_list($db, $count);
    }

    public function edit() {
        $id = I('get.id', 0, 'intval');
        $info = M($this->table)->find($id);
        $user_info = M('user')->find($info['user_id']);
        if (IS_POST) {
            $return = array('info' => '充值失败！', 'status' => 0);
            M()->startTrans(); //开启事务
            try {
                $amount = I('post.change_amount', '', 'trim');
                $user_amount = $user_info['amount'];
                $data1 = array('amount' => $user_amount + $amount);
                $where1 = array('id' => $user_info['id']);
                $result1 = M('user')->where($where1)->save($data1);
                if ($result1 === false) {
                    //用户余额充值失败
                    E('充值失败！');
                }
                $data2 = array(
                    'status' => 1,
                    'star_amount' => $user_amount,
                    'transaction_amount' => $amount,
                    'amount' => $data1['amount'],
                    'processing_time' => time()
                );
                $where2 = array('id' => $id);
                $result2 = M($this->table)->where($where2)->save($data2);
                if ($result2 === false) {
                    //订单状态修改失败
                    E('充值失败！');
                }
                M()->commit(); //提交事务
                $return['status'] = 1;
                $return['info'] = '充值成功！';
            } catch (\Exception $e) {
                M()->rollback(); //回滚
                $return['status'] = 0;
                $return['info'] = $e->getMessage();
            }
            $this->ajaxReturn($return);
        } else {
            $this->assign('userinfo', $user_info);
            $this->display();
        }
    }

    public function del() {
        if (DataService::update($this->table)) {
            $this->success('删除成功！');
        }
        $this->error('删除失败！');
    }

}
